<template>
	<view class="mapping-details" ref="uv-back-top">
		<uv-navbar v-if="!isPc" title="成图" @rightClick="routed('/pages/mapping/history')" rightText="历史"
			leftIconSize="10px" :placeholder="true" @leftClick="navigateBack"></uv-navbar>


		<view class="content">
			<lsj-edit ref="lsjEdit" placeholder="输入正文" :maxCount="200" @onReady="editReady">
				<template v-slot:btns="data">
					<edit-btns :edit="data.edit" @click="onTabClick" @submit="save"></edit-btns>
				</template>
			</lsj-edit>
			<view style="height: 50px;width: 100%;cursor: pointer;" @click="uploadFile">
				<uv-icon size="30" style="margin: 10px;" name="photo"></uv-icon>
			</view>
			<view>
				<button @click="chooseAndUpload">上传图片</button>
				<image v-if="imageUrl" :src="imageUrl" mode="aspectFit"></image>
			</view>
			{{content}}
			<mp-html v-if="content" :content="content.html" />
			<!-- <editor id="editor" class="ql-container" placeholder="开始输入..." show-img-size show-img-toolbar
				show-img-resize @statuschange="onStatusChange" :read-only="readOnly" @ready="onEditorReady">
			</editor> -->

			<!-- <iframe
				src="http://192.168.30.239/chat/share?shared_id=ed294606f36711efaae50242ac120002&from=chat&auth=RiM2ViOWVjZjQzMTExZWY4YjY5MDI0Mm"
				style="width: 100%; height: 100%; min-height: 600px" frameborder="0">
			</iframe> -->
		</view>
		<uv-back-top :scroll-top="scrollTop"></uv-back-top>
		<tabbars :prop-value="'mapping'"></tabbars>
	</view>
</template>

<script>
	// 引入
	import editBtns from '@/uni_modules/lsj-edit/components/lsj-edit/edit-btns/edit-btns.vue';
	import tabbars from '@/components/tabbar/tabbar.vue';
	import config from '@/common/config'
	import {
		uploadFileName,
		postName
	} from '@/common/api.js';
	import {
		uploadFileToOSS
	} from '@/util/oss.js';
	export default {
		components: {
			// 注册组件
			tabbars,
			// 富文本基本操作按键，可自行选择是否使用示例的按键
			editBtns
		},
		data() {
			return {
				scrollTop: 0,
				value: 'qeqwarawrf',
				edit: null,
				content: null,
				// 上传
				CHUNK_SIZE: 1024 * 1024 * 5,
				file: null,
				fileHash: '',
				totalChunks: '',

				// 上传2
				imageUrl: ''
			}
		},
		computed: {},
		onLoad() {},
		onPageScroll(e) {
			this.scrollTop = e.scrollTop;
			// #ifdef APP-NVUE
			this.scrollTop = e.detail.scrollTop;
			// #endif
		},
		methods: {
			async chooseAndUpload() {
				// 选择文件
				const [chooseErr, chooseRes] = await uni.chooseImage({
					count: 1,
					sizeType: ['compressed'],
					sourceType: ['album']
				});
				console.log(chooseErr, chooseRes)
				if (chooseErr) {
					uni.showToast({
						title: '选择文件失败',
						icon: 'none'
					});
					return;
				}

				const tempFilePath = chooseRes.tempFilePaths[0];
				uni.showLoading({
					title: '上传中...'
				});

				try {
					// 上传到OSS
					this.imageUrl = await uploadFileToOSS(tempFilePath);
					uni.hideLoading();
					uni.showToast({
						title: '上传成功'
					});
				} catch (error) {
					uni.hideLoading();
					uni.showToast({
						title: error.message,
						icon: 'none'
					});
				}
			},
			convertToBinaryAndUpload(filePath) {
				uni.getFileSystemManager().readFile({
					filePath: filePath,
					encoding: 'base64',
					success: (res) => {
						const base64Data = res.data;
						const binaryData = dataURLtoBlob(base64Data);
					}
				});
			},
			dataURLtoBlob(dataurl) {
				var arr = dataurl.split(","),
					mime = arr[0].match(/:(.*?);/)[1],
					bstr = atob(arr[1]),
					n = bstr.length,
					u8arr = new Uint8Array(n);
				while (n--) {
					u8arr[n] = bstr.charCodeAt(n);
				}
				return new Blob([u8arr], {
					type: mime,
				});
			},
			// 文件分片函数
			sliceFile(file) {
				const chunks = [];
				let start = 0;
				while (start < file.size) {
					const end = Math.min(start + this.CHUNK_SIZE, file.size);
					const chunk = file.slice(start, end);
					chunks.push({
						chunk,
						index: chunks.length,
						start,
						end
					});
					start = end;
				}
				return chunks;
			},
			// 选择文件后处理
			async uploadFile() {
				const fileRes = await uni.chooseVideo({
					sourceType: ['album', 'camera'],
					compressed: false
				});

				const file = fileRes; // 注意：uniapp返回的是临时路径
				console.log('选择的文件:', fileRes);
				// 需要先将文件转为ArrayBuffer进行处理
				const chunks = await this.sliceFile(file.tempFile);

				// 上传每个分片
				for (const chunkInfo of chunks) {
					await this.uploadChunk(chunkInfo, file.name, chunks.length);
				}

				// 通知后端合并分片
				await this.mergeChunks(file.name, chunks.length);
			},
			async uploadChunk(chunkInfo, fileName, totalChunks) {
				let formData = {
					index: chunkInfo.index,
					fileName: fileName,
					totalChunks: totalChunks
				};
				try {
					let res = await uploadFileName('chunk/upload', {
						custom: {
							auth: true,
							catch: true
						},
						name: 'chunk',
						// name: 'image',
						file: chunkInfo.chunk,
						formData
					})
					// const res = await uni.request({
					// 	url: 'http://localhost:8080/dpc/chunk/upload',
					// 	method: 'POST',
					// 	data: formData,
					// 	// header: {
					// 	// 	'Content-Type': 'multipart/form-data'
					// 	// }
					// });

					console.log(`分片 ${chunkInfo.index} 上传成功`);
				} catch (error) {
					console.error(`分片 ${chunkInfo.index} 上传失败:`, error);
					throw error;
				}
			},
			async mergeChunks(fileName, totalChunks) {
				try {
					const res = await postName('/chunk/merge', {
						fileName,
						totalChunks
					});
					console.log(res);
					if (res) {
						console.log('文件上传完成:', res);
						// 更新UI，显示上传成功
					}
				} catch (error) {
					console.error('文件合并失败:', error);
					throw error;
				}
			},

			getContents() {
				this.content = this.edit.getContents();
			},
			// 编辑器初始化完毕，返回edit对象
			editReady(edit) {
				// 将富文本对象存放到当前页面，便于后续直接操作
				this.edit = edit;
			},
			// 演示----按钮组件点击事件
			onTabClick({
				name,
				index
			}) {
				switch (index) {
					// 插入#话题#
					case 0:
						this.addLink();
						break;
						// @某人
					case 1:
						this.addLink2();
						break;
					default:
						break;
				}
			},
			// 演示发布
			async save() {
				// 获取插入的图片列表
				let imgs = await this.edit.getImages()
				// 判断是否允许提交
				if (!this.edit.textCount && !imgs.length) {
					uni.showToast({
						title: '请录入内容'
					});
				}
				this.content = await this.edit.getContents();
				// 将所有未上传的本地图片上传到服务器并替换到编辑器
				this.edit.replaceImage(async (img) => {
					// 已上传的无需再上传
					// 这里没有放到edit内部去过滤，因为我觉得需不需要上传得你自己决定
					// 比如插入的base64图片是否需要上传
					// img.indexOf('http') = 0说明这个图片已经是网络地址，无需替换就直接跳过
					if (img.indexOf('http') === 0) {
						return img;
					}
					let upfile = await uploadFile('', {
						custom: {
							auth: true,
							catch: true
						},
						name: 'image',
						filePath: img,
						formData: {
							type: 'image'
						},
					})
					console.log(upfile);
					return upfile.url;

					// 上传并替换图片
					/* 
					    let {data} = await uni.uploadFile({
					        url: 'https://www.example.com/upload', //仅为示例，非真实的接口地址
					        filePath: img, //本地图片
					        name: 'file',
					        formData: {
					            'user': 'test'
					        }
					    });
					    return data;
					 */

					// 因为演示的时候没有服务器，所以直接换个网络图方便后续演示，
					// 实际项目应使用上方注释内容
					return 'https://t7.baidu.com/it/u=3406125714,2513313326&fm=193&f=GIF'

				}).then(res => {
					console.log('替换完成,最终内容为', JSON.stringify(res));

					// 示例项目可查看解析富文本演示
					// uni.navigateTo({
					// 	url: '/pages/article/article?data=' + escape(res.html)
					// });
				});

			},
			// 插入话题示例
			addLink() {
				this.edit.addLink({
					prefix: '#',
					suffix: '#',
					link: "https://www.json.cn",
					name: '有问题欢迎加入LSJ插件交流群',
					data: {
						name: 'QQ交流群',
						qqGroupChatID: '667530868',
					}
				})
			},
			// @某人示例
			addLink2() {
				this.edit.addLink({
					prefix: '@',
					name: '马冬梅',
					data: {
						userId: 10,
					}
				})
			},
			routed(url) {
				uni.$uv.route({
					url: url,
					intercept(params, next) {
						console.log(params, next)
						uni.showLoading({
							title: '等待中...'
						})
						// 模拟处理等待
						setTimeout(() => {
							uni.hideLoading();
							next(true);
						}, 1000)
					}
				})
			}
		}
	}
</script>

<style scoped lang="scss">
	.mapping-details {
		// width: calc(100% - 20px);
		// padding: 10px;

	}

	// 测试
	.bg-purple {
		background: #CED7E1;
	}

	.bg-purple-light {
		background: #e5e9f2;
	}

	.bg-purple-dark {
		background: #99a9bf;
	}
</style>